# coding:utf8

from hdfs import InsecureClient
from config import hdfs_url
from time_format import timestamp_datetime
import datetime


def get_hdfs_path(url=hdfs_url, path=None):
    client = InsecureClient(url, user='liumiao')
    content = client.walk(path)
    nodes = []
    for node in content:
        dirs = node[1]
        files = node[2]
        for dir in dirs:
            path_new = path + '/' + dir if path != '/' else path + dir
            status = client.status(path_new)
            nodes.append(
                {"label": dir,
                 "id": path_new,
                 "info": '( ' + status['owner'] + ': ' + status['group'] + ' | ' + timestamp_datetime(
                     status['modificationTime'] / 1000) + ' | ' + status['permission'] + ' | ' + str(
                     status['childrenNum']) + ' files )',
                 "load_on_demand": True})
        for file in files:
            path_new = path + '/' + file if path != '/' else path + file
            status = client.status(path_new)
            nodes.append({"label": file,
                          "id": path_new,
                          "info": ' (' + status['owner'] + ': ' + status['group'] + ' | ' + timestamp_datetime(
                              status['modificationTime'] / 1000) + ' | ' + status[
                                      'permission'] + ' | ' + bytes_to_other(
                              status['length']) + ')'})
        break
    return nodes


def bytes_to_other(value):
    if value < 1024:
        return str(value) + ' B'
    elif 1024 <= value < 1024 * 1024:
        return str('%.2f' % (value / 1024.0)) + ' KB'
    elif 1024 * 1024 <= value < 1024 * 1024 * 1024:
        return str('%.2f' % (value / 1024.0 / 1024)) + ' MB'
    elif 1024 * 1024 * 1024 <= value:
        return str('%.2f' % (value / 1024.0 / 1024 / 1024)) + ' GB'



